﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebUtils;

namespace OAuth
{
    internal static class Utilities
    {
        static readonly DateTime BEGINNING_OF_TIME = new DateTime(1970, 1, 1, 0, 0, 0, 0);


        /// <summary>
        /// takes a string that looks like this: aoeu=aoeu&oeui=oeui&qjk=qjk and returns an iterable with the Parameters
        /// </summary>
        /// <param name="pParameterString"></param>
        /// <returns></returns>
        public static IEnumerable<UnEncodedURLParameter> ParseParameters(string pParameterString)
        {
            if (string.IsNullOrEmpty(pParameterString))
                return new UnEncodedURLParameter[] { };
            else
                return from pairArray in
                           (from pairStr in pParameterString.Split('&')
                            select pairStr.Contains('=') ? pairStr.Split('=') : new string[] { pairStr, string.Empty })
                       select new UnEncodedURLParameter()
                       {
                           Key = pairArray[0],
                           Value = pairArray[1]
                       };
        }

        internal class TimeStampNonce
        {
            public string Timestamp { get; set; }
            public string Nonce { get; set; }
        }

        /// <remarks>
        /// 8.  Nonce and Timestamp
        /// 
        /// Unless otherwise specified by the Service Provider, the timestamp is expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value MUST be a positive integer and MUST be equal or greater than the timestamp used in previous requests.
        /// 
        /// The Consumer SHALL then generate a Nonce value that is unique for all requests with that timestamp. A nonce is a random string, uniquely generated for each request. The nonce allows the Service Provider to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel (such as HTTP). 
        /// </remarks>
        internal static TimeStampNonce ToUnixTimeStampAndNonce(this DateTime pDateTime)
        {
            // Default implementation of UNIX time of the current UTC time
            TimeSpan ts = pDateTime.ToUniversalTime() - BEGINNING_OF_TIME;
            string timeStamp = ts.TotalSeconds.ToString();
            int length = timeStamp.IndexOf(".") > -1 ? timeStamp.IndexOf(".") : timeStamp.Length;
            timeStamp = timeStamp.Substring(0, length);

            return new TimeStampNonce()
            {
                Nonce = timeStamp /*+ Guid.NewGuid().ToString()*/,
                Timestamp = timeStamp 
            };
        }

    }
}
